package design.simdi.code.final_paper.utils;

import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractToolbar;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import design.simdi.code.final_paper.core.entities.Person;
import design.simdi.code.final_paper.core.entities.User;
import design.simdi.code.final_paper.core.services.UserService;
import design.simdi.code.final_paper.site.application.MyAuthenticatedWebSession;

/**
 * 
 * @author Marius Dumitriu - (Jun 19, 2010 - 2:13:56 AM)
 * 
 */
public abstract class ActionToolbar extends AbstractToolbar {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@SpringBean
	private UserService userService;

	public ActionToolbar(IModel<?> model, MyDataTable<?> table) {
		super(model, table);
		init();
	}

	public ActionToolbar(MyDataTable<?> table) {
		super(table);
		init();
	}

	private void init() {
		ListView<ToolbarItem> listaItems = new ListView<ToolbarItem>("toolbarItems", getItemsList()) {

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<ToolbarItem> item) {
				final ToolbarItem toolbarItem = item.getModelObject();
				AjaxFallbackLink<String> link = new AjaxFallbackLink<String>("link") {

					private static final long serialVersionUID = 1L;

					@Override
					public void onClick(AjaxRequestTarget target) {
						onAction(toolbarItem, target);
					}

				};
				StaticImage image = new StaticImage("image", new Model<String>(toolbarItem.getImageSource()));

				link.add(image);
				link.add(new SimpleAttributeModifier("title", getToolbarName(toolbarItem)));
				item.add(link);

			}
		};
		add(listaItems);

	}

	public abstract void onAction(ToolbarItem toolbarItem, AjaxRequestTarget target);

	public abstract List<ToolbarItem> getItemsList();

	public abstract String getToolbarName(ToolbarItem toolbarItem);

	protected MyDataTable<?> getTable() {
		return (MyDataTable<?>) super.getTable();
	}

	public Person getCurrentPerson() {
		User currentUser = ((MyAuthenticatedWebSession) getSession()).getCurrentUser();

		Person p = getUserService().findPersonByUser(currentUser);
		return p;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

}
